package com.controller;
import com.dao.MsgDao;
import com.dao.UserDao;
import com.pojo.Msg;
import com.pojo.Result;
import com.utils.DateUtils;
import com.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.utils.MessageUtils.*;

@RestController
@RequestMapping("/msg")
public class MsgController {

    @Autowired
    private MsgDao msgDao;

    @Autowired
    private UserDao userDao;

    @GetMapping("/{page}/{pageSize}")
    public Result getByPage(@PathVariable int page, @PathVariable int pageSize,HttpServletRequest request){
        String userId = request.getSession().getAttribute("user").toString();
        String nickName = getNickName(userId);
        page=(page-1)*pageSize;
        List<Msg> msgs = msgDao.getByPage(page, pageSize,nickName);
        int total = msgDao.getCount(nickName);
        Map<String, Object> map = new HashMap<>();
        map.put("msgs",msgs);
        map.put("total",total);
        return Result.success(SELECT_DATA_SUCCESS,map);
    }

    @PostMapping
    public Result add(@RequestBody Msg msg, HttpServletRequest request){
        String userId = request.getSession().getAttribute("user").toString();
        msg.setSender(getNickName(userId));
        msg.setTime(DateUtils.now());
        msgDao.add(msg);
        return Result.success(ADD_DATA_SUCCESS);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id){
        msgDao.delete(id);
        return Result.success(DELETE_DATA_SUCCESS);
    }

    private String getNickName(String userId){
        return userDao.getBYIdOrEMail(userId).getNickName();
    }
}
